package open.witype.filetiper.activity.home.adapter;

import android.content.Context;
import android.os.Environment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import java.util.List;
import java.util.Stack;

import open.witype.filetiper.R;
import open.witype.filetiper.fragment.file.FileFragment;
import open.witype.filetiper.fragment.file.loader.FileLoader;
import open.witype.filetiper.model.FileItemBean;

/**
 * Created by Typer on 2015/5/26 0026.
 * 文件浏览Fragment的适配器
 */
public class HomeFragmentAdapter {

    private Stack<String> paths = new Stack<>();
    ;

    private Stack<FileFragment> fragments = new Stack<>();
    ;

    private FragmentManager fm;

    private int resContainer;

    private String root = Environment.getExternalStorageDirectory().getPath();

    private Context context;

    public HomeFragmentAdapter(FragmentManager fm, int resContainer, Context context) {
        this.fm = fm;
        this.context = context;
        this.resContainer = resContainer;
        addItem(root);
    }

    private FileFragment fragment;

    /**
     * 增加一个FileFragment页面
     *
     * @param path 目录地址
     */
    public void addItem(String path) {
        if (paths.contains(path))
            return;
        paths.push(path);
        //一个新的fragment
        fragment = getItem();
        FileLoader loader = new FileLoader(onLoaderFinish);
        loader.execute(path);
        fragments.push(fragment);
    }

    /**
     * 删除一个fragment
     *
     * @return 是否是顶层的文件夹
     */
    public boolean deleteItem() {
        boolean result;
        if (getPathCount() == 1) {
            result = true;
        } else {
            paths.pop();
            FileFragment fragment = fragments.pop();
            FragmentTransaction ft = fm.beginTransaction();
            ft.setCustomAnimations(R.anim.fragment_left_enter, R.anim.fragment_left_exit);
            ft.remove(fragment);
            ft.commit();
            result = false;
        }
        return result;
    }

    private FileLoader.OnLoaderFinish onLoaderFinish = new FileLoader.OnLoaderFinish() {
        @Override
        public void onLoadFinish(List<FileItemBean> fileItemBeans) {
            fragment.setRecyclerAdapter(fileItemBeans, context);
            FragmentTransaction ft = fm.beginTransaction();
            ft.setCustomAnimations(R.anim.fragment_right_enter, R.anim.fragment_right_exit);
            ft.add(resContainer, fragment);
            ft.commit();
        }
    };

    /**
     * 获得fragments的size
     *
     * @return 当前的FileFragment的size
     */
    public int getPathCount() {
        return paths.size();
    }

    /**
     * 获得一个新的对象
     * 新的对象默认两个参数为 path为paths顶端的地址，index为paths的顶端的索引
     *
     * @return 新的页面
     */
    public FileFragment getItem() {
        FileFragment fragment = FileFragment.newInstance(paths.peek());
        fragment.setPath(paths.peek());
        return fragment;
    }
}
